﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Xml;
using System.Web;
using System.IO;

namespace DragDraw.Service
{
    public class ErrorMsg
    {
        public int ErrorID;
        public string ErrorMessage;
        public ErrorMsg()
        {
            ErrorID = 0;
            ErrorMessage = "";
        }
        public ErrorMsg(int errorID, string errorMessage)
        {
            ErrorID = errorID;
            ErrorMessage = errorMessage;
        }
    }
    /// <summary>
    /// 用户服务，为客户端处理各类请求
    /// 每一个用户访问，wcf会new一个Service，
    /// </summary>
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class UserService : IUserService
    {
        const int USER_IS_NULL = 0;//用户为空null
        const int USERID_IS_EMPTY = 1;//用户ID为null或者是空串
        const int USER_REALNAME_IS_EMPTY = 2;//用户Realname为null或者是空串
        const int USERID_NOTFOUND = 3;//数据库里找不到用户ID
        const int USER_PASSWORD_IS_EMPTY = 4;//用户密码是空的
        const int USER_INSERT_FAIL = 5;//用户已经存在，插入失败
        const int USERINFO_DELETE_FAILD = 13;//删除用户失败
        const int USERID_NOT_MATCH_PASSWORD = 14;//用户ID和密码不对应
        const int SPACE_NOTFOUND = 6;//找不到空间
        const int SPACE_IS_NULL = 7;//空间为空null
        const int SPACEID_NOT_FOUND = 15;//空间ID不存在
        const int WIDGETINFO_NOT_FOUND = 8;//找不到widgetInfo
        const int WIDGETID_NOT_MATCH_SPACEID = 9;//widgetID 和　spaceID不匹配
        const int WIDGETID_IS_NOTFOUND = 10;//找不到widgetID
        const int WIDGET_INSERT_FAIL = 16;//Widget插入失败
        const int WIDGET_IS_NULL = 11;//widget为空null
        const int FRIEDNLIST_IS_EMPTY = 12;//朋友列表为空


        // 记录用户错误信息
        private Stack<string> ErrorMsgStack = new Stack<string>();
        private Stack<ErrorMsg> ErrorMsgIDStack = new Stack<ErrorMsg>();

        public ErrorMsg getErrorMsgID()
        {
            if (ErrorMsgIDStack.Count != 0)
                return ErrorMsgIDStack.Pop();
            else return null;
        }

        public string getErrorMsg()
        {
            if (ErrorMsgStack.Count != 0)
                return ErrorMsgStack.Pop();
            else return "";
        }


        public UserService()
        {
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="username">用户ID</param>
        /// <param name="password">密码</param>
        /// <returns>登陆是否成功</returns>
        public bool Login(string username, string password)
        {
            if (username == "" || username == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_IS_EMPTY, "用户ID为null或者是空串"));
                return false;
            }
            if (password == "" || password == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USER_PASSWORD_IS_EMPTY, "密码是空的"));
                return false;
            }
            try
            {
                // 密码是否与用户对应
                if (password == UserAccountData.Query(username))
                    return true;
                else
                {
                    ErrorMsgIDStack.Push(new ErrorMsg(USERID_NOT_MATCH_PASSWORD, "登录，但用户ID和密码不匹配"));
                    return false;
                }
            }
            catch (DataNotFoundException e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_NOTFOUND, "登录，但用户ID不存在"));
                ErrorMsgStack.Push("账号不存在");
                return false;
            }
            catch (Exception e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_NOTFOUND, "登录2，但用户ID不存在"));
                ErrorMsgStack.Push(e.Message);
                return false;
            }
            //　登录失败
            return false;
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        /// <param name="password">用户密码</param>
        /// <returns>注册是否成功</returns>
        public bool Register(UserInfo userInfo, string password)//finished
        {
            if (userInfo == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USER_IS_NULL, "用户为空null"));
                return false;
            }
            if (password == "" || password == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USER_PASSWORD_IS_EMPTY, "密码是空的"));
                return false;
            }
            // 用户ID和密码都不能为空
            if (userInfo.UserID == "" || userInfo.UserID == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_IS_EMPTY, "用户ID为空"));
                return false;
            }
            if (userInfo.Realname == "" || userInfo.Realname == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USER_PASSWORD_IS_EMPTY, "密码是空的"));
                return false;
            }
            try
            {
                UserInfoData.Insert(userInfo);//Insert a new UserInfo
            }
            catch (DataInsertException e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USER_INSERT_FAIL, "用户已经存在，插入失败(插入用户失败)"));
                ErrorMsgStack.Push("账号名已经被使用");
                return false;
            }
            catch (Exception e)
            {
                ErrorMsgStack.Push(e.Message);
                return false;
            }
            try
            {
                UserAccountData.Insert(userInfo.UserID, password);
            }
            catch (DataInsertException e)// 插入用户和密码失败
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USER_INSERT_FAIL, "用户已经存在，插入失败(设置密码失败)"));
                ErrorMsgStack.Push("账号名已经被使用");
                try
                {
                    UserInfoData.Delete(userInfo.UserID);// 把之前插入的用户删除
                }
                catch (DataErrorException e2)
                {
                    ErrorMsgStack.Push(e2.Message);                    
                }
                return false;
            }
            catch (Exception e)
            {
                UserInfoData.Delete(userInfo.UserID);// 把之前插入的用户删除                
                ErrorMsgStack.Push(e.Message);
                return false;
            }
            SpaceInfo temp_spaceInfo = new SpaceInfo();
            temp_spaceInfo.OwnerUserID = userInfo.UserID;
            temp_spaceInfo.BackgroundImage = "";
            temp_spaceInfo.ThemeColor = "FFFFFF";

            int spaceID = 0;
            try
            {
                spaceID = SpaceInfoData.Insert(temp_spaceInfo);// 插入空间
            }
            // 如果插入空间失败
            catch (Exception e)
            {
                // 把之前插入的用户还有帐号密码都删除
                UserInfoData.Delete(userInfo.UserID);
                UserAccountData.Delete(userInfo.UserID);
                ErrorMsgStack.Push(e.Message);
                return false;
            }
            // 注册成功
            return true;
        }

        // 删除用户
        public bool DeleteUserInfo(string userID)
        {
            /*if (userID == "")
                return false;
            if (UserInfoData.Query(userID) == null)
                return false;
            SpaceInfo space;
            try
            {
                // 查询用户对应的space
                space = SpaceInfoData.Query(userID);
                //　查询space中的widget
                List<WidgetInfo> widgetList = WidgetInfoData.QueryList(space.SpaceID);
                //　删除space中所有的widget
                foreach (WidgetInfo wid in widgetList)
                {
                    this.DeleteWidgetInfo(space.SpaceID, wid.WidgetID);
                }
                // 删除用户的空间
                SpaceInfoData.Delete(space.SpaceID);
                //　删除用户
                UserInfoData.Delete(userID);
                //　删除成功
                return true;
             catch (Exception e)
            {
                //　删除过程有失败
                ErrorMsgStack.Push(e.Message);
                return false;
            }*/
            if (userID == "" || userID == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_IS_EMPTY, "删除用户，用户ID为空"));
                return false;
            }
            else try
                {
                    UserInfoData.Delete(userID);
                    return true;
                }
                catch (DataErrorException e)
                {
                    ErrorMsgIDStack.Push(new ErrorMsg(USERINFO_DELETE_FAILD, "删除用户，用户删除失败"));
                    ErrorMsgStack.Push(e.Message);
                }
            return false;
        }

        /// <summary>
        /// 设置用户信息
        /// </summary>
        /// <param name="user">新的用户信息</param>
        /// <returns>设置是否成功</returns>
        public bool SetUserInfo(UserInfo user)
        {
            // 如果用户为空
            if (user == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USER_IS_NULL, "设置用户，用户是null用户"));
                return false;
            }
            // 如果用户ID和Realname为空
            if (user.UserID == "" || user.UserID == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_IS_EMPTY, "设置用户，用户ID是空"));
                return false;
            }
            if (user.Realname == "" || user.Realname == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USER_REALNAME_IS_EMPTY, "设置用户，用户名是空的"));
                return false;
            }
            // 如果用户不存在，返回false
            try
            {
                // 查询用户的ID是否存在
                UserInfoData.Query(user.UserID);
            }
            catch (Exception e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_NOTFOUND, "设置用户，找不到用户ID"));
                return false;
            }
            try
            {
                //　更新用户资料
                UserInfoData.Update(user);
                //　更新成功
                return true;
            }
            //　在更新过程中有失败
            catch (Exception e)
            {
                ErrorMsgStack.Push(e.Message);
                return false;
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userID">用户的ID</param>
        /// <returns>返回UserInfo,用户的信息</returns>
        public UserInfo GetUserInfo(string userID)
        {

            if (userID == "" || userID == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_IS_EMPTY, "获取用户信息，用户ID是空的"));
                return null;
            }
            UserInfo user;
            try
            {
                // 查询用户
                user = UserInfoData.Query(userID);
                if (user == null)
                {
                    ErrorMsgStack.Push("获取用户信息，找不到指定的用户信息");
                }
                return user;
            }
            catch (DataNotFoundException e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_NOTFOUND, "获取用户信息，找不到用户ID"));
                ErrorMsgStack.Push("找不到指定的用户信息");
            }
            catch (Exception e)
            {
                ErrorMsgStack.Push(e.Message);
            }
            return null;
        }

        /// <summary>
        /// 获取所有用户的ID
        /// </summary>
        /// <returns>所有用户的ID列表</returns>
        public List<string> GetUserList()
        {
            try
            {
                return UserInfoData.GetAllUserInfo();
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 设置用户密码
        /// </summary>
        /// <param name="userID">用户的ID</param>
        /// <param name="password">要设的密码</param>
        /// <returns>成功则返true</returns>
        public bool SetPassword(string userID, string password)
        {
            // 如果用户为空 或者 密码为空 或者 户不存在
            if (userID == "" || userID == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_IS_EMPTY, "设置密码，但用户名是空"));
                return false;
            }
            else if (password == "" || password == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USER_PASSWORD_IS_EMPTY, "设置密码，但用户密码为空"));
                return false;
            }
            try
            {
                // 查询用户是否存在，不存在就会抛出异常
                UserInfoData.Query(userID);
            }
            //　!!!!!!!!!!!!**********此处异常捕捉不到
            catch (DataNotFoundException e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_NOTFOUND, "设置密码，用户ID不存在"));
                ErrorMsgStack.Push(e.Message);
                return false;
            }
            catch (Exception e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_NOTFOUND, "设置密码2，用户ID不存在"));
                ErrorMsgStack.Push(e.Message);
                return false;
            }
            try
            {
                //　更改用户密码
                UserAccountData.Update(userID, password);
                // 更改过程没有异常，更改成功
                return true;
            }
            //　更改过程中有异常
            catch (Exception e)
            {
                ErrorMsgStack.Push(e.Message);
                return false;
            }
        }

        /// <summary>
        /// 获得userID的空间信息
        /// </summary>
        /// <param name="userID">用户密码</param>
        /// <returns>空间信息，失败则返回null</returns> 
        public SpaceInfo GetSpaceInfo(string userID)//finished 
        {
            if (userID == "" || userID == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_IS_EMPTY, "获取空间信息，但用户名是空"));
                return null;
            }
            try
            {
                // 查询空间
                SpaceInfo space = SpaceInfoData.Query(userID);
                return space;
            }
            catch (DataNotFoundException e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(SPACE_NOTFOUND, "获取空间，但找不到"));
                ErrorMsgStack.Push("找不到指定的空间信息");
            }
            catch (Exception e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(SPACE_NOTFOUND, "获取空间2，但找不到"));
                ErrorMsgStack.Push(e.Message);
            }
            return null;
        }

        /// <summary>
        /// 设置空间
        /// </summary>
        /// <param name="spaceInfo">新的空间信息</param>
        /// <returns>设置是否成功</returns> 
        public bool SetSpaceInfo(SpaceInfo spaceInfo)
        {
            if (spaceInfo == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(SPACE_IS_NULL, "设置空间，空间为空null"));
                return false;
            }
            // 空间已存在就更新
            SpaceInfo space;
            try
            {
                space = SpaceInfoData.Query(spaceInfo.OwnerUserID);
                if (space.SpaceID != spaceInfo.SpaceID)
                {
                    ErrorMsgIDStack.Push(new ErrorMsg(SPACEID_NOT_FOUND, "设置空间信息，空间ID和用户ID不匹配"));
                    return false;
                }
            }
            catch (DataNotFoundException e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_NOTFOUND, "设置空间信息，找不到用户ID"));
                return false;
            }
            catch (Exception E)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_NOTFOUND, "设置空间信息，找不到用户ID"));
                ErrorMsgStack.Push(E.Message);
                return false;
            }
            try
            {
                SpaceInfoData.Update(spaceInfo);
                return true;
            }
            // 空间不存在就插入
            catch (Exception e)
            {
                try
                {
                    // 如果空间的拥有者的ID不存在，抛出异常
                    UserInfoData.Query(spaceInfo.OwnerUserID);
                    // 插入空间，失败就会抛出异常
                    SpaceInfoData.Insert(spaceInfo);
                    return true;
                }
                catch (Exception e2)
                {
                    //　空间插入失败
                    ErrorMsgStack.Push(e2.Message);
                    return false;
                }
            }
        }

        /// <summary>
        /// 获得空间的小工具列表
        /// </summary>
        /// <param name="spaceID">空间ID</param>
        /// <returns>空间小工具列表，失败则返回null</returns>
        public List<WidgetInfo> GetWidgetList(int spaceID)
        {
            try
            {
                return WidgetInfoData.QueryList(spaceID);
            }
            catch (DataNotFoundException e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(WIDGETINFO_NOT_FOUND, "获得空间小工具列表，找不到小工具"));
                return new List<WidgetInfo>();// return empty list
            }
            catch (Exception e)
            {
                ErrorMsgStack.Push(e.Message);
                return null;
            }
        }

        /// <summary>
        /// 为某个空间增加一个小工具
        /// 为指定space（在widgetInfo.OwnerSpaceID确定）增加一个widget，
        /// 注意，要为小工具指定工具库的ID,不然添加会失败
        /// 忽略输入参数中的widgetID，由数据库分配新ID并返回，失败返回-1
        /// </summary>
        /// <param name="widgetInfo"></param>
        /// <returns></returns>
        public int AddWidgetInfo(WidgetInfo widgetInfo)
        {
            try
            {
                // 存储所有用户的userID
                List<string> userID;
                userID = UserInfoData.GetAllUserInfo();
                SpaceInfo space;
                foreach (string ID in userID)
                {
                    // 检查widgetInfo中的spaceID是否存在
                    space = SpaceInfoData.Query(ID);
                    if (widgetInfo.OwnerSpaceID == space.SpaceID)
                    {
                        // 插入widgetInfo
                        try
                        {
                            return widgetInfo.WidgetID = WidgetInfoData.Insert(widgetInfo);
                        }
                        catch (Exception)
                        {

                        }
                    }
                }
                ErrorMsgStack.Push("小工具创建失败，找不到相应空间");
            }
            // widgetInfo中的spaceID不存在
            catch (Exception e)
            {
                ErrorMsgStack.Push(e.Message);
            }
            return -1;
        }

        /// <summary>
        /// 根据ID删除一个widgetInfo，返回成功与否
        /// </summary>
        /// <param name="spaceID"></param>
        /// <param name="widgetID"></param>
        /// <returns></returns>
        public bool DeleteWidgetInfo(int spaceID, int widgetID)
        {
            WidgetInfo widget;
            try
            {
                // 如果widgetID与spaceID无法匹配，认为是失败
                widget = WidgetInfoData.Query(widgetID);
            }
            catch (DataNotFoundException e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(WIDGETID_IS_NOTFOUND, "删除WidgetInfo,但找不到WidgetID"));
                ErrorMsgStack.Push(e.Message);
                return false;
            }
            catch (Exception e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(WIDGETID_IS_NOTFOUND, "删除WidgetInfo2,但找不到WidgetID"));
                ErrorMsgStack.Push(e.Message);
                return false;
            }
            try
            {
                // 如果spaceID与widgetID匹配
                if (spaceID == widget.OwnerSpaceID)
                    // 进行删除操作
                    return WidgetInfoData.Delete(widgetID);
                else
                {
                    ErrorMsgIDStack.Push(new ErrorMsg(WIDGETID_NOT_MATCH_SPACEID, "删除widgetInfo,但widgetID和spaceID不匹配"));
                    return false;
                }
            }
            catch (Exception e)
            {
                // 删除失败
                ErrorMsgStack.Push(e.Message);
            }
            return false;
        }

        /// <summary>
        /// 根据widgetInfo中的widgetID更新一个widgetInfo，返回成功与否
        /// （注意不能修改OwnerSpaceID，如果发现有此类修改，视为错误）
        /// </summary>
        /// <param name="widgetInfo"></param>
        /// <returns></returns>
        public bool UpdateWidgetInfo(WidgetInfo widgetInfo)
        {
            // 如果widgetInfo为空，返回false
            if (widgetInfo == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(WIDGET_IS_NULL, "更新widget，但widget为空null"));
                return false;
            }

            // 存储所有用户的userID
            List<string> userID;
            userID = UserInfoData.GetAllUserInfo();
            try
            {
                SpaceInfo space;
                foreach (string ID in userID)
                {
                    // 检查spaceID是否存在
                    space = SpaceInfoData.Query(ID);
                    // spaceID存在，更新小工具
                    if (widgetInfo.OwnerSpaceID == space.SpaceID)
                    {
                        return WidgetInfoData.Update(widgetInfo);
                    }
                }
            }
            catch (DataNotFoundException e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(SPACE_NOTFOUND, "更新widget,但用户ID没有对应的space"));
                ErrorMsgStack.Push("小工具信息更新失败，找不到相应信息");
            }
            catch (Exception e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(SPACE_NOTFOUND, "更新widget2,但用户ID没有对应的space"));
                ErrorMsgStack.Push(e.Message);
            }
            return false;
        }

        /// <summary>
        /// 获取指定的会话
        /// </summary>
        /// <param name="widgetID">小工具ID</param>
        /// <param name="sessionName">会话名称</param>
        /// <returns>会话的值</returns>
        public string GetSession(int widgetID, string sessionName)//finished
        {
            try
            {
                return WidgetSessionData.Query(widgetID, sessionName);
            }
            catch (DataNotFoundException e)
            {
            }
            catch (Exception e)
            {
                ErrorMsgStack.Push(e.Message);
            }
            return "";
        }

        /// <summary>
        /// 更新会话信息
        /// </summary>
        /// <param name="widgetID">会话所属的小工具的ID</param>
        /// <param name="sessionName">会话名称</param>
        /// <param name="sessionValue">会话值</param>
        /// <returns>设置是否成功</returns>
        public bool SetSession(int widgetID, string sessionName, string sessionValue)//finished
        {
            try
            {
                WidgetInfoData.Query(widgetID);
            }
            catch(Exception e)
            {            
                ErrorMsgStack.Push(e.Message);
                    return false;
            }
            try
            {
                if (WidgetSessionData.Update(widgetID, sessionName, sessionValue))
                    return true;
            }
            catch(Exception e)
            {
                ErrorMsgStack.Push("会话更新失败");

                try
                {
                    if (WidgetSessionData.Insert(widgetID, sessionName, sessionValue))
                        return true;
                }
                catch (DataNotFoundException e2)
                {
                    ErrorMsgStack.Push("会话更新失败，找不到相应的小工具");
                }
                catch (Exception e3)
                {
                    ErrorMsgStack.Push(e3.Message);
                }
            }            
            return false;
        }

        /// <summary>
        /// 获取指定用户的朋友列表
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns>好友列表，失败返回null</returns>
        public List<string> GetFriendList(string userID)
        {
            if (userID == "" || userID == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_IS_EMPTY, "获取朋友列表，但userID为空"));
                return null;
            }
            try
            {
                // 如果userID为空，或者userID用户不存在，返回null
                if (UserInfoData.Query(userID) != null)
                    return FriendRelationData.QueryList(userID);
            }
            catch (DataNotFoundException e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(FRIEDNLIST_IS_EMPTY, "获取朋友列表，但朋友列表为空"));
                return new List<string>();// return empty list
            }
            catch (Exception e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(FRIEDNLIST_IS_EMPTY, "获取朋友列表2，但朋友列表为空"));
                ErrorMsgStack.Push(e.Message);
            }
            ErrorMsgStack.Push("获取好友列表失败，请求的用户ID不存在");
            return null;
        }

        /// <summary>
        /// 为requestUserID增加一个朋友，目标为friendID
        /// 如果关系已经存在，返回false
        /// 两者的顺序对调也视为同一关系，数据库将会自动判断
        /// </summary>
        /// <param name="requestUserID"></param>
        /// <param name="friendID"></param>
        /// <returns></returns>
        public bool AddFriend(string requestUserID, string friendID)
        {
            if (requestUserID == "" || requestUserID == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_IS_EMPTY, "添加朋友，但请求方的ID的空"));
                return false;
            }
            if (friendID == "" || friendID == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_IS_EMPTY, "添加朋友，但添加对象的ID为空"));
                return false;
            }
            // 首先判断两ID是否存在
            try
            {
                if (UserInfoData.Query(requestUserID) != null
                    && UserInfoData.Query(friendID) != null)
                    return FriendRelationData.Insert(requestUserID, friendID);
            }
            catch (DataNotFoundException e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_NOTFOUND, "添加朋友，但双方的ID有一方不存在"));
                ErrorMsgStack.Push(e.Message);
            }
            catch (DataInsertException e)
            {
                ErrorMsgStack.Push("朋友关系已经存在");
            }
            catch (Exception e)
            {
                ErrorMsgStack.Push(e.Message);
            }
            return false;
        }

        /// <summary>
        /// 删除一个朋友关系
        /// 不存在返回false
        /// </summary>
        /// <param name="requestUserID"></param>
        /// <param name="friendID"></param>
        /// <returns>删除是否成功</returns>
        public bool DelFriend(string requestUserID, string friendID)
        {
            if (requestUserID == "" || requestUserID == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_IS_EMPTY, "删除朋友，但请求方的ID的空"));
                return false;
            }
            if (friendID == "" || friendID == null)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_IS_EMPTY, "删除朋友，但添加对象的ID为空"));
                return false;
            }
            try
            {
                // 首先判断两ID是否存在
                if (UserInfoData.Query(requestUserID) != null
                    && UserInfoData.Query(friendID) != null)
                    return FriendRelationData.Delete(requestUserID, friendID);
            }
            catch (DataNotFoundException e)
            {
                ErrorMsgIDStack.Push(new ErrorMsg(USERID_NOTFOUND, "删除朋友，但双方有一方的ID不存在"));
                ErrorMsgStack.Push(e.Message);
            }
            catch (Exception e)
            {
                ErrorMsgStack.Push(e.Message);
            }
            return false;
        }

        public string UploadFile(string userID, string filename, byte[] data)
        {
            using (FileStream stream = new FileStream(@"e:\WorkSpace\WebRoot\Files\" + filename, FileMode.Create))
            {
                stream.Write(data, 0, data.Length);
                stream.Close();
            }
            return @"e:\WorkSpace\WebRoot\Files\" + filename;
        }

        // 发送一个系统消息，系统消息的IsHandled属性自动初始化为false
        public bool SendMessage(string srcID, string destID, string tag, string body)
        {
            try
            {
                // 检查发送者和接收者是否存在
                if (UserInfoData.Query(srcID) != null && UserInfoData.Query(destID) != null)
                {
                    // 检查tag和body是否为空
                    if (tag != "" && body != "")
                    {
                        SysMessage message = new SysMessage();
                        message.SourceID = srcID;
                        message.DestinationID = destID;
                        message.Tag = tag;
                        message.Body = body;
                        message.IsHandled = false;
                        return SysMessageData.Insert(message);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorMsgStack.Push(e.Message);
            }
            return false;
        }

        // 返回所有Message，注意返回之后要将数据库所有Message标记IsHandled（但返回的结果不要标记）
        // !!!!******还没有完成
        public List<SysMessage> GetMessageList(string userID)
        {
            try
            {
                // 判断此userID是否存在
                if (UserInfoData.Query(userID) != null)
                {
                    // !!!!!!!**********还没有完成
                    // 注意返回之后要将数据库所有Message标记IsHandled（但返回的结果不要标记）
                    List<SysMessage> listMsg = SysMessageData.QueryList(userID);
                    foreach (SysMessage msg in listMsg)
                    {
                        msg.IsHandled = true;
                    }
                }
            }
            catch (DataNotFoundException e)
            {
                return new List<SysMessage>();
            }
            catch (Exception e)
            {
                ErrorMsgStack.Push(e.Message);
            }
            return null;
        }

        /// <summary>
        /// 获取网站系统的设置
        /// </summary>
        /// <returns>系统设置</returns>
        public SystemSetting GetSystemSetting()
        {
            string path = ServerUtils.GetLocalPath("config.xml");
            SystemSetting sys = null;
            try
            {
                XmlReader reader = XmlReader.Create(path);
                sys = new SystemSetting();
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        sys.Version = reader.GetAttribute("Version");
                        sys.SystemUserID = reader.GetAttribute("SystemUserID");
                        sys.WidgetFolderUrl = reader.GetAttribute("WidgetFolderUrl");
                        sys.FileFolderUrl = reader.GetAttribute("FileFolderUrl");
                        sys.WidgetLibList = WidgetLibInfoData.Query();
                        return sys;
                    }
                }
                throw new Exception();
            }
            // 有异常，则是因为文件不存在，新建此文件
            catch (Exception e)
            {
                sys = new SystemSetting();
                sys.Version = "1.000";
                sys.SystemUserID = "system";
                sys.WidgetFolderUrl = "http://localhost/ClientBin/";
                sys.FileFolderUrl = "http://localhost/";
                sys.WidgetLibList = WidgetLibInfoData.Query();
            }
            return sys;
        }

        /// <summary>
        /// 返回最后一次的错误消息
        /// </summary>
        /// <returns>最后一次错误消息</returns>
        public string GetLastError()
        {
            if (ErrorMsgStack.Count > 0)
            {
                return ErrorMsgStack.Pop();
            }
            return "";
        }

    }
}
